package wang.unclecat.hello;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Date;

import timber.log.Timber;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);

        checkEnv();

        Intent intent = getIntent();

        //对应IntentParams params = new IntentParams();  params.setParam("androidFile1","androidFile1----");
        Timber.d("onCreate() called with: intent.getStringExtra(\"androidFile1\") = [ %s ]", intent.getStringExtra("androidFile1"));

        //对应operation.withUri(Uri.parse("https://www.baidu.com"))
        Timber.d("onCreate() called with: intent.getData() = [ %s ]", intent.getData());

        //对应operation.withEntities(stringSet)
        Timber.d("onCreate() called with: intent.getCategories() = [ %s ]", intent.getCategories());

        intentParams("onCreate", intent.getExtras());

        findViewById(R.id.go2ohos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                //CardAbility有对应的代理类CardAbilityShellActivity，我们可以这样理解。
                ComponentName componentName = new ComponentName("wang.unclecat.hello","wang.unclecat.mycard.CardAbilityShellActivity");
                intent.putExtra("msg","鸿蒙哥哥，我是安卓");
                intent.setComponent(componentName);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
                startActivity(intent);
            }
        });

        findViewById(R.id.connect2ohos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                ComponentName componentName = new ComponentName("wang.unclecat.hello","wang.unclecat.mycard.ServiceAbilityShellService");
                intent.setComponent(componentName);
                bindService(intent, connection, Context.BIND_AUTO_CREATE);
            }
        });

        findViewById(R.id.send2ohos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (serviceBinder!=null) {
                    Parcel data = Parcel.obtain();
                    Parcel reply = Parcel.obtain();
                    data.writeString("time:"+new Date().getTime());
                    try {
                        serviceBinder.transact(2, data, reply, IBinder.FLAG_ONEWAY);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

    }

    private IBinder serviceBinder;
    /** Defines callbacks for service binding, passed to bindService() */
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName className,
                                       IBinder service) {
            serviceBinder = service;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            serviceBinder = null;
        }
    };
    public static void intentParams(String tag, Bundle params) {
        if (params==null) {
            return;
        }
        StringBuilder sb = new StringBuilder();
        sb.append("params--->");
        sb.append("\n");
        for (String key : params.keySet()) {
            sb.append(key).append(" = ").append(params.get(key));
            sb.append("\n");
        }
        sb.append("<---params");
        Timber.d("intentParams() called with: tag = [ %s ], params = [ %s ]", tag, sb.toString());
    }

    private void checkEnv() {
        if (isOhos()) {
            textView.setText("当前系统环境为：鸿蒙");
        } else {
            textView.setText("当前系统环境为：安卓。\n\n亲爱的安卓用户，鸿蒙2.0向你招手");
        }
    }

    public static boolean isOhos() {
        boolean isOhos = false;
        try {
            Class<?> abilityClass = Class.forName("ohos.aafwk.ability.Ability");
            ClassLoader classLoader = abilityClass.getClassLoader();

            //如果Ability为系统提供的，其classloader为BootClassLoader
            //如果Ability为伪造的，其classloader一般为PathClassLoader
            System.out.println("abilityClassLoader: " + classLoader);

            //BootClassLoader的parent为null
            if (classLoader != null && classLoader.getParent() == null) {
                isOhos = true;
            }
        } catch (ClassNotFoundException ignored) {
        }

        return isOhos;
    }
}